﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class LoginControl : System.Web.UI.UserControl
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        
        this.DisplayDate();
        tbUsername.Attributes.Add("onFocus", "ClearField(this)");
        tbPass.Attributes.Add("onFocus", "ClearField(this)");
        if (!IsPostBack)
        {
            this.Display();
        }                 
    }

    void Display()
    {
        DataTable dtb = (DataTable)Session["Userlogin"];
        MultiView1.ActiveViewIndex = (dtb == null) ? 0 : 2;
        if (dtb != null)
        {
            lblUsername.Text = dtb.Rows[0]["FullName"].ToString();
        }
    }

    void DisplayDate()
    {
        String dayofweek = DateTime.Now.DayOfWeek.ToString();
        String day = DateTime.Now.Day.ToString();
        String month = DateTime.Now.Month.ToString();
        String year = DateTime.Now.Year.ToString();
        lblDate.Text = dayofweek+", Ngày " + day + " tháng " + month + " năm " + year; 
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        String sql = @"SELECT * FROM customers WHERE CustomerID=@username AND PassWord=@password";
        String username = tbUsername.Text;
        String password = tbPass.Text;

        DataTable dtb = DataBase.GetDataTable(sql, "@username", username, "@password", password);
        if (dtb.Rows.Count > 0)
        {
            Session["Userlogin"] = dtb;
            lblUsername.Text = dtb.Rows[0]["FullName"].ToString();
            MultiView1.ActiveViewIndex = 2;
            if (Request.Url.AbsoluteUri.EndsWith("ViewCart.aspx"))
            {
                Response.Redirect("ViewCart.aspx");
            }
            //if (Request.Url.AbsoluteUri.EndsWith("Account.aspx"))
            else
            {
                //string url = HttpContext.Current.Request.Url.ToString();
                //Response.Redirect(url);
                Response.Redirect("Account.aspx");
            }            
        }
        else
        {
            MultiView1.ActiveViewIndex = 1;
        }
        
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 0;
        tbUsername.Text = "Username";
        tbPass.Text = "Password";
    }

    protected void btnLogout_Click(object sender, EventArgs e)
    {
        Session.Remove("Userlogin");
        ShoppingCart cart = (ShoppingCart)Session["ShoppingCart"];
        cart.Clear();
        string path = HttpContext.Current.Request.Url.ToString();
        Response.Redirect(path);
    }
    
}
